package com.mercycrazy.recruit.filter;

import com.alibaba.fastjson2.JSON;
import com.mercycrazy.recruit.user.SimpleAdminInfo;
import com.mercycrazy.recruit.user.UserInfo;
import com.mercycrazy.recruit.util.SwaggerUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

import static com.mercycrazy.recruit.constant.CommonConstant.*;

/**
 * 用户身份统一拦截
 *
 * @author <a href="mailto:1443424326@qq.com">mercycrazy</a>
 * @since 2023-01-16
 */
@Slf4j
@Component
public class LoginUserInfoInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {

        // 放行 Swagger 请求
        if (SwaggerUtil.checkSpringDocUrl(request.getRequestURI())) {
            return true;
        }

        // 先尝试从 http header 里面获取用户登录信息
        String userInfoStr = request.getHeader(JWT_USER_INFO_KEY);
        String platform = request.getHeader(LOGIN_PLATFORM);

        // 设置当前用户请求上下文
        if (StringUtils.isNotBlank(userInfoStr)) {
            userInfoStr = URLDecoder.decode(userInfoStr, StandardCharsets.UTF_8.name());
            log.info("set login user info: [{}], platform: [{}]",
                    userInfoStr, platform);

            if (Objects.equals(platform, ADMIN_JWT_PREFIX)) {
                AccessContext.setLoginAdminInfo(
                        JSON.parseObject(userInfoStr, SimpleAdminInfo.class)
                );
            } else {
                AccessContext.setLoginUserInfo(
                        JSON.parseObject(userInfoStr, UserInfo.class)
                );
            }

            AccessContext.setLoginPlatform(platform);
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {

        if (null != AccessContext.getLoginUserInfo()
                || null != AccessContext.getLoginAdminInfo()
                || null != AccessContext.getLoginPlatform()) {

            AccessContext.clear();
        }
    }
}
